﻿using Prism.Commands;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace SmartPlantApp.ViewModels
{
    public class ServerSwitchViewModel : DialogViewModelBase, IDialogAware
    {
        private DelegateCommand<object> _pageLoadCommand;
        private readonly IOAuthService _authService;
        private ObservableCollection<DropDownListObj> _serverList;
        private DropDownListObj _selObj = null;

        public ServerSwitchViewModel(IOAuthService oAuthService, IDialogService dialogService) : base(dialogService)
        {
            Title = "选择服务器";
            _authService = oAuthService;
            _serverList = new ObservableCollection<DropDownListObj>();
        }

        public DropDownListObj CurrentSelect
        {
            get { return _selObj; }
            set { SetProperty(ref _selObj, value); }
        }

        public ObservableCollection<DropDownListObj> ServerList
        {
            get
            {
                return _serverList;
            }
        }

        public ICommand PageLoadCommand
        {
            get
            {
                if (_pageLoadCommand != null) return _pageLoadCommand;
                _pageLoadCommand = new DelegateCommand<object>(OnPageLoadCommand);
                return _pageLoadCommand;
            }
        }

        private async void OnPageLoadCommand(object obj)
        {
            var configs = await _authService.GetConfigsAsync();
            ServerList.Clear();
            if (configs != null && configs.Count > 0)
            {
                foreach (var config in configs)
                {
                    ServerList.Add(new DropDownListObj { Id = config.configId, Name = config.configId });
                }
            }
        }

        protected async override void onCloseDialogCommand(string parameter)
        {
            if (CurrentSelect == null)
            {
                Dialog.ShowAltert($"未选择任何需要切换服务器。");
                return;
            }

            string configId = "";
            ButtonResult result = ButtonResult.None;
            if (parameter?.ToLower() == "ok")
            {
                try
                {
                    configId = await _authService.SwitchServerAsync(CurrentSelect.Id);
                }
                catch (Exception x)
                {
                    Dialog.ShowAltert($"切换服务器失败：{x.Message}");
                    return;
                }


                result = ButtonResult.OK;
            }
            else if (parameter?.ToLower() == "cancel")
                result = ButtonResult.Cancel;
            RaiseRequestClose(new DialogResult(result, new DialogParameters($"configId={configId}")));
        }
    }
}
